package com.qf.cdmmybatisspringbootstarter.config;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.Map;

public class MapperScannerConfigurerRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        //向BeanDefinitionRegistry中注入一个MapperScannerConfigurer类型的BeanDefinition
//        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition();
//        rootBeanDefinition.setBeanClass(MapperScannerConfigurer.class);
//        registry.registerBeanDefinition("msc",rootBeanDefinition);

        //上述方式无法向MapperScannerConfigurer中动态设置扫描包
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);

        //向MapperScannerConfigurer设置扫描包
        Map<String, Object> map = metadata.getAnnotationAttributes(EnableMapperScan.class.getName());
        String basePackage = (String) map.get("basePackage");

        builder.addPropertyValue("basePackage", basePackage);

        AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
        registry.registerBeanDefinition("msc",beanDefinition);
    }
}
